package com.yxy.handler;

import com.yxy.common.Result;
import com.yxy.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.ReflectionException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public ResponseEntity<Result> exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        Result<Object> error = Result.error(ex.getMessage());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }

    /**
     * 捕获sql异常
     * @param ex
     */
    @ExceptionHandler
    public ResponseEntity<Result> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error("Sql异常信息：{}", message);
        return new ResponseEntity<>(Result.error(message), HttpStatus.INTERNAL_SERVER_ERROR);
    }


    /**
     * 捕获反射异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public ResponseEntity<Result> exceptionHandler(ReflectionException ex){
        String message = ex.getMessage();
        log.error("反射异常信息：{}", message);
        return new ResponseEntity<>(Result.error("服务器错误，请联系管理员"), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
